package com.example.wac.controller;

import com.example.wac.annotation.UnJwtToken;
import com.example.wac.entity.common.ReqDTO;
import com.example.wac.enums.ErrorCode;
import com.example.wac.service.login.LoginStrategy;
import com.example.wac.util.JwtUtil;
import com.example.wac.vo.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @author wuancheng
 * @description 常用于直接微信小程序公众号等直接登录获取token
 * @date 2021-12-31 15:54:00
 */

@RestController
@RequestMapping("/token")
public class TokenController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    LoginStrategy loginStrategy;

    @UnJwtToken
    @PostMapping("/type_token")
    public ApiResult getTokenByType(@RequestBody ReqDTO dto){
        /**
         * 工厂+模版方法
         */
        return ApiResult.success(loginStrategy.getByType(dto.getString("type")));
    }

    /**
     * 根据userID得到token
     *
     * @param id
     * @return
     */
    @GetMapping("/token")
    public String getToken(@RequestParam("id") String id){
        Optional.ofNullable(id).orElseThrow(ErrorCode.PARAM_CANNOT_EMPTY::getAppException);
        //跳过验证id是否存在环节
        String token = JwtUtil.createJWT(id);
        String key = "token-" + id;
        if (redisTemplate.hasKey(key)){
            String tokenBefore = (String) redisTemplate.opsForValue().get(key);
            return tokenBefore;
        }else {
            redisTemplate.opsForValue().set(key,token);
        }
        return token;
    }

    /**
     * 根据userID刷新token
     *
     * @param id
     * @return
     */
    @GetMapping("/fresh_token")
    public String getFreshToken(@RequestParam("id") String id){
        Optional.ofNullable(id).orElseThrow(ErrorCode.PARAM_CANNOT_EMPTY::getAppException);
        String key = "token-" + id;
        String token = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isBlank(token)){
            throw ErrorCode.TOKEN_INVALID.getAppException();
        }else {
            String freshSign = JwtUtil.freshSign(token);
            redisTemplate.opsForValue().set(key,freshSign);
            return freshSign;
        }
    }
}
